module.exports = app => {
  const express = require('express')
  const jwt = require('jsonwebtoken')
  const assert = require('http-assert')
  const AdminUser = require('../../models/AdminUser')
  const router = express.Router({
    mergeParams: true
  })
  
  const authMiddleware = require('../../middleware/auth') // 校验中间件
  const resourceMiddleware = require('../../middleware/resource') // 模块选择中间件
  app.use('/admin/api/rest/:resource', authMiddleware(app), resourceMiddleware(), router)

  /* 通用接口开始-------------------------------------------------------------------------------- */
  //创建
  router.post('/', async (req, res) => {
    const model = await req.Model.create(req.body)
    res.send(model)
  })
  // 修改数据
  router.put('/:id', async (req, res) => {
    await req.Model.findByIdAndUpdate(req.params.id, req.body)
    res.send({
      code: 200,
      data: "操作成功",
      msg: "操作成功"
    })
  })
  //查询
  router.get('/', async (req, res) => {
    const queryOptions = {}
    if (req.Model.modelName === 'Category') {
      queryOptions.populate = 'parent'  
    }
    if (req.Model.modelName === 'Article') {
      queryOptions.populate = 'categories' 
    }
    var items = await req.Model.find().setOptions(queryOptions).limit(100)
    if (req.query.type === 'hero') {
      items = items.filter(item => item.parent && item.parent.name === '英雄')
    }
    if (req.query.type === 'news') {
      items = items.filter(item => item.parent && item.parent.name === '资讯')
    }
    if (req.query.type === 'parent') {
      items = items.filter(item => item.parent === undefined)
    }
    res.send({
      code: 200,
      data: items,
      msg: "查询成功"
    })
  })
  // 编辑数据获取
  router.get('/:id', async (req, res) => {
      const model = await req.Model.findById(req.params.id)
      res.send(model)
  })
  // 删除数据
  router.delete('/:id', async (req, res) => {
      await req.Model.deleteOne({_id:req.params.id})
      res.send({
        code: 200,
        data: '删除成功',
        msg: '删除成功'
      })
  })
  /* 通用接口结束-------------------------------------------------------------------------------- */
  
  // 图片上传
  const multer = require('multer')
  const upload = multer({dest:__dirname + '/../../uploads'}) //文件上传保存
  app.post('/admin/api/upload', authMiddleware(app), upload.single('file'), async (req, res) => {
    const file = req.file
    file.url = `http://localhost:3000/uploads/${file.filename}`
    res.send(file)
  })

  // 登陆验证
  app.post('/admin/api/login', async (req, res) => {
    const { username, password } = req.body
    const user = await AdminUser.findOne({username}).select('+password')
    assert(user, 422, '用户不存在')
    const isValid = require('bcryptjs').compareSync(password, user.password) // 密码验证
    assert(isValid, 422, '密码错误')
    // 返回token
    const token = jwt.sign({ id: user._id}, app.get('secret'))
    res.send({token})
  })

  // 错误处理
  app.use(async (err, req, res, next) => {
    res.status(err.statusCode || 500).send({
      message: err.message
    })
  })
}